import type { SiteData } from './interface'
import { stores } from '@/stores'
import * as Storage from '@/storage'
import { fetchSiteInfo } from '@/api/base'

/** 初始化站点信息 */
export const initSiteInfo = async () => {
    const localSiteInfo: SiteData | undefined = Storage.getLocalStorage('SITE_INFO')

    /** 站点数据请求间隔 */
    const UPDATE_INTERVAL = 1 * 60 * 1000
    const lastUpdateTime = Number(localSiteInfo?.request_time || 0)
    const isNeedUpdate = new Date().getTime() - lastUpdateTime > UPDATE_INTERVAL

    if (localSiteInfo && !isNeedUpdate) {
        stores.siteStore.updateSiteData(localSiteInfo)
        return
    }

    const { data } = await fetchSiteInfo()
    stores.siteStore.updateSiteData(data)
    return
}

/** 获取站点Title */
export const getSiteTitle = () => {
    const { website } = stores.siteStore.siteData
    console.log(website)

    const suffix: Record<typeof BUILD_ENV, string> = {
        dev: '-开发系统',
        test: '-测试系统',
        pre: '-预发布系统',
        pro: '',
    }

    const title = `${website}${suffix[BUILD_ENV]}`

    return title
}

export const setSiteTitle = () => {
    document.title = getSiteTitle()
}
